package com.projectName.www.service;

import com.projectName.www.po.orders;
import com.projectName.www.servlet.Y_J;
import com.projectName.www.util.String_util;
import com.projectName.www.dao.Y_J_intoshop_dao;

import javax.swing.*;
import javax.swing.GroupLayout.Alignment;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.Document;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.ResultSet;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Vector;

/**
     * @author 86132
     *
     */
    public class Y_J_intoshop extends JInternalFrame {
        private JTable dishes_table;
        private JTable coupons_table;
        private JTextField num;
        private JTextField paymoney;
        private JTextField dishename;
     private  static int i;
     private  boolean getcoupon=false;//是否一键领取过优惠券
    private  boolean user=true;//优惠券使用与否
    private boolean message=false;//是否可以留言
           private       JTextArea textArea;
        /**
         * Launch the application.
         */

        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    try {
                        Y_J_intoshop frame = new Y_J_intoshop();
                        frame.setVisible(true);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        /**
         * Create the frame.
         */
        public Y_J_intoshop() throws Exception {

            setClosable(true);

            setBounds(100, 100, 986, 573);

            JDesktopPane desktopPane = new JDesktopPane();
            desktopPane.setBackground(SystemColor.inactiveCaptionBorder);
            GroupLayout groupLayout = new GroupLayout(getContentPane());
            groupLayout.setHorizontalGroup(
                    groupLayout.createParallelGroup(Alignment.LEADING)
                            .addGroup(groupLayout.createSequentialGroup()
                                    .addContainerGap()
                                    .addComponent(desktopPane, GroupLayout.DEFAULT_SIZE, 956, Short.MAX_VALUE)
                                    .addContainerGap())
            );
            groupLayout.setVerticalGroup(
                    groupLayout.createParallelGroup(Alignment.LEADING)
                            .addComponent(desktopPane, GroupLayout.DEFAULT_SIZE, 544, Short.MAX_VALUE)
            );

            JScrollPane scrollPane = new JScrollPane();
            scrollPane.setBounds(10, 28, 435, 362);
            desktopPane.add(scrollPane);

            dishes_table = new JTable();

            dishes_table.addMouseListener(new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    //按表编辑
                    try {
                        i=dishes_table.getSelectedRow();
                      filldata(i);
                    } catch (Exception ex) {
                        throw new RuntimeException(ex);
                    }}});
            dishes_table.setModel(new DefaultTableModel(
                    new Object[][] {
                            {null, null, null},
                            {null, null, null},
                            {null, null, null},
                            {null, null, null},
                            {null, null, null},
                            {null, null, null},
                            {null, null, null},
                            {null, null, null},
                            {null, null, null},
                            {null, null, null},
                            {null, null, null},
                            {null, null, null},
                            {null, null, null},
                            {null, null, null},
                            {null, null, null},
                            {null, null, null},
                            {null, null, null},
                            {null, null, null},
                            {null, null, null},
                            {null, null, null},
                            {null, null, null},
                    },
                    new String[] {
                            "\u83DC\u540D", "\u4EF7\u683C", "\u83DC\u54C1\u63CF\u8FF0"
                    }
            ) {
                boolean[] columnEditables = new boolean[] {
                        false, false, true
                };
                public boolean isCellEditable(int row, int column) {
                    return columnEditables[column];
                }
            });
            dishes_table.getColumnModel().getColumn(0).setPreferredWidth(60);
            dishes_table.getColumnModel().getColumn(1).setPreferredWidth(35);
            dishes_table.getColumnModel().getColumn(2).setPreferredWidth(101);
            scrollPane.setViewportView(dishes_table);

            JLabel lblNewLabel = new JLabel("");
            lblNewLabel.setFont(new Font("宋体", Font.BOLD | Font.ITALIC, 23));
            lblNewLabel.setBounds(38, 28, 54, 15);
            desktopPane.add(lblNewLabel);

            JScrollPane scrollPane_1 = new JScrollPane();
            scrollPane_1.setBounds(512, 28, 404, 108);
            desktopPane.add(scrollPane_1);

            coupons_table = new JTable();
            coupons_table.setModel(new DefaultTableModel(
                    new Object[][] {
                            {null, null},
                            {null, null},
                            {null, null},
                            {null, null},
                            {null, null},
                            {null, null},
                            {null, null},
                            {null, null},
                            {null, null},
                            {null, null},
                    },
                    new String[] {
                            "\u4F18\u60E0\u5238", "\u622A\u6B62\u4F7F\u7528\u65F6\u95F4"
                    }
            ) {
                boolean[] columnEditables = new boolean[] {
                        false, false
                };
                public boolean isCellEditable(int row, int column) {
                    return columnEditables[column];
                }
            });
            scrollPane_1.setViewportView(coupons_table);

            JButton getcou = new JButton("一键领取");
            getcou.addActionListener(e -> {
                try {
                    getcoupons(e);
                } catch (Exception ex) {
                    throw new RuntimeException(ex);
                }
            });
            getcou.setFont(new Font("宋体", Font.BOLD | Font.ITALIC, 55));
            getcou.setBounds(522, 146, 335, 73);
            desktopPane.add(getcou);

             textArea = new JTextArea();
            textArea.setBounds(519, 229, 338, 121);
            desktopPane.add(textArea);

            JButton make_message = new JButton("写评论");
            make_message.addActionListener(e -> {
                try {
                    message(e);
                } catch (Exception ex) {
                    throw new RuntimeException(ex);
                }
            });
            make_message.setFont(new Font("宋体", Font.BOLD | Font.ITALIC, 55));
            make_message.setBounds(522, 360, 335, 73);
            desktopPane.add(make_message);

            num = new JTextField();


            num.setBounds(78, 457, 66, 21);
            desktopPane.add(num);
            num.setColumns(10);

            JLabel lblNewLabel_1 = new JLabel("数量：");
            lblNewLabel_1.setBounds(38, 460, 54, 15);
             desktopPane.add(lblNewLabel_1);

            JLabel lblNewLabel_1_1 = new JLabel("支付金额：");
            lblNewLabel_1_1.setBounds(10, 488, 82, 15);
            desktopPane.add(lblNewLabel_1_1);

            paymoney = new JTextField();
            paymoney.setEditable(false);
            paymoney.setColumns(10);
            paymoney.setBounds(78, 485, 66, 21);
            desktopPane.add(paymoney);

            JButton make_order = new JButton("下单");

            make_order.setFont(new Font("宋体", Font.BOLD | Font.ITALIC, 55));
            make_order.setBounds(522, 443, 346, 59);
            desktopPane.add(make_order);

            JLabel lblNewLabel_1_2 = new JLabel("菜名：");
            lblNewLabel_1_2.setBounds(38, 431, 54, 15);
            desktopPane.add(lblNewLabel_1_2);
            num.setText("1");
            dishename = new JTextField();
            dishename.setEditable(false);
            dishename.setColumns(10);
            dishename.setBounds(78, 428, 130, 21);
            desktopPane.add(dishename);

            JButton use_coupon = new JButton("是否使用优惠券（随机使用)");

            use_coupon.setBounds(254, 400, 191, 60);
            JButton buycar = new JButton("加入购物车");
            buycar.setBounds(254, 470, 191, 60);
            desktopPane.add(use_coupon);
            desktopPane.add(buycar);
            getContentPane().setLayout(groupLayout);
            filldishes_table();
            fillcoupons_table();
            //文本修改监听事件
            Document d = num.getDocument();
            d.addDocumentListener(new DocumentListener() {
                //输入数量改变支付金额
                @Override
                public void insertUpdate(DocumentEvent e) {

                    filldata(i);

                }

                @Override
                public void removeUpdate(DocumentEvent e) {

                }

                @Override
                public void changedUpdate(DocumentEvent e) {


                }
            });
            use_coupon.addActionListener(e-> {
                int n=String_util.num(num.getText());
                try {
                    if(user&&n>0) {

                        usecoupon();
                       user=false;
                        JOptionPane.showMessageDialog(null,"使用成功");
                    }
                    else if(n<=0)
                    {
                        JOptionPane.showMessageDialog(null,"使用失败：请检查数量");
                    }
                    else JOptionPane.showMessageDialog(null,"一次只能使用一张优惠券");
                } catch (Exception ex) {
                    throw new RuntimeException(ex);
                }
            });
            make_order.addActionListener(e -> {
                try {
                    int k=1;
                    int j=0;
                    boolean makeorder = makeorder(k,j);
                    if(makeorder){user=true;
                        message=true;

                        filldata(i);
                        Y_J.upmoney();
                        JOptionPane.showMessageDialog(null,"下单成功");}
                    else JOptionPane.showMessageDialog(null,"下单失败：请检查账户或者数量");
                } catch (Exception ex) {
                    throw new RuntimeException(ex);
                }
            });
            buycar.addActionListener(e->
            {
                try {
                    int i=0;
                    int j=1;
                    boolean makeorder = makeorder(i,j);
                    if(makeorder){
                        user=true;
                        filldata(i);
                        JOptionPane.showMessageDialog(null,"加入成功");}
                    else JOptionPane.showMessageDialog(null,"加入失败：请检查数量");
                } catch (Exception ex) {
                    throw new RuntimeException(ex);
                }

            });

        }

        //下单&&加入购物车
    public boolean makeorder(int i,int j) throws Exception {
        orders r=new orders();
        r.setBuyers(OpenBuyer.username);
        r.setBusiness(Y_J.findingname);
        r.setDishename(dishename.getText());
        r.setMoney(String_util.num(paymoney.getText()));
        r.setBool_shop(i);
        r.setBool_buyer(j);
        r.setNum(String_util.num(num.getText()));
        if(r.getNum()>0) {
            boolean getorder = Y_J_intoshop_dao.getorder(r);

             return getorder;
        }
        else return false;
    }


    //获取点击菜品信息
    private void filldata(int i ) {
        dishename.setText((String) dishes_table .getValueAt(i,0));

        int  money =String_util.num((String) dishes_table .getValueAt(i,1));

        int  num = String_util.num(this.num.getText());

        if (num >0)

        paymoney.setText(""+num*money);
        else paymoney.setText("");
    }

    //写评论
    private void message(ActionEvent e) throws Exception {
       if(message&&Y_J_intoshop_dao.makemessage(textArea.getText(),Y_J.findingname,OpenBuyer.username))
           JOptionPane.showMessageDialog(null,"评价成功");
        else JOptionPane.showMessageDialog(null,"评价失败：还未下单或者留言为空");

    }
    //领取优惠券
    private void getcoupons(ActionEvent e) throws Exception {


            if(!getcoupon&&Y_J_intoshop_dao.getcoupon(Y_J.findingname)&&Y_J_intoshop_dao.username(OpenBuyer.username,Y_J.findingname))
            {
                JOptionPane.showMessageDialog(null,"领取成功");
                getcoupon=true;
                fillcoupons_table();


            }
            else JOptionPane.showMessageDialog(null,"领取失败");
    }

    //填充优惠券表格
        public void fillcoupons_table()throws Exception {

                ResultSet fillcoupons = Y_J_intoshop_dao.fillcoupons(Y_J.findingname);
                DefaultTableModel model = (DefaultTableModel) coupons_table.getModel();
                model.setRowCount(0);
                while (fillcoupons.next()) {

                    if (!getcoupon&&fillcoupons.getInt("num") > 0) {
                        Vector V = new Vector();
                        V.add(fillcoupons.getString("coupon"));
                        V.add(fillcoupons.getString("finaltime"));
                        model.addRow(V);
                    }



                }
            }



        //填充菜品表格
        public void filldishes_table() throws Exception {
            ResultSet r = Y_J_intoshop_dao.filldishes(Y_J.findingname);
            DefaultTableModel model = (DefaultTableModel) dishes_table.getModel();
            model.setRowCount(0);
            while (r.next()) {
                Vector v = new Vector();
                v.add(r.getString("name"));
                v.add(r.getString("money"));
                if (r.getString("des") != null) {
                    v.add(r.getString("des"));
                } else v.add("");
                model.addRow(v);
            }

        }
        //使用优惠券
    public void  usecoupon() throws Exception {

            ResultSet coupon = Y_J_intoshop_dao.coupon(OpenBuyer.username, Y_J.findingname);

            while (coupon.next()) {
                boolean updatecoupon = Y_J_intoshop_dao.updatecoupon(OpenBuyer.username, Y_J.findingname, coupon.getString("finaltime"));
                String finaltime = coupon.getString("finaltime") + " 00:00:00";
                DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                LocalDateTime l1 = LocalDateTime.parse(finaltime, df);
                LocalDateTime l2 = LocalDateTime.now();


                boolean after = l1.isAfter(l2);
                if (after && updatecoupon) {
                   int  coupon1 = coupon.getInt("coupon");//获取优惠金额
                    int  num = String_util.num(paymoney.getText());//获取当前支付金额
                    if((num - coupon1)>=0) {
                        paymoney.setText("" + (num - coupon1));
                    }
                    else paymoney.setText("0");
                    break;
                }

            }

    }

}
